package com.example.lotterysystem.service.activitystatus.operator;

import com.example.lotterysystem.dao.dataobject.ActivityUserDO;
import com.example.lotterysystem.dao.mapper.ActivityUserMapper;
import com.example.lotterysystem.service.dto.ConvertActivityStatusDTO;
import com.example.lotterysystem.service.enums.ActivityUserStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@Slf4j
public class UserOperator extends AbstractActivityOperator {
    @Autowired
    private ActivityUserMapper activityUserMapper;

    @Override
    public Integer sequence() {
        return 1;
    }

    @Override
    public Boolean needConvert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        Long activityId = convertActivityStatusDTO.getActivityId();
        List<Long> userIds = convertActivityStatusDTO.getUserIds();
        ActivityUserStatusEnum targetUserStatus = convertActivityStatusDTO.getTargetUserStatus();
        // 活动 id 、中奖人员列表 和 目标状态是否为空
        if (null == activityId
                || CollectionUtils.isEmpty(userIds)
                || null == targetUserStatus) {
            log.warn("needConvert 中 活动id、中奖人员列表 或目标状态为空");
            return false;
        }
        // 中奖人员是否存在
        List<ActivityUserDO> activityUserDOList = activityUserMapper.selectByAUId(activityId, userIds);
        if (CollectionUtils.isEmpty(activityUserDOList)) {
            log.warn("needConvert 中 {} 活动 中奖人员 {} 不存在", activityId, userIds);
        }
        // 中奖人员状态是否需要转化
        for (ActivityUserDO activityUserDO: activityUserDOList) {
            if (targetUserStatus.name().
                    equalsIgnoreCase(activityUserDO.getStatus())) {
                log.warn("needConvert 中 {} 活动 {} 用户已被抽取", activityId, activityUserDO.getUserId());
                return false;
            }
        }

        // 校验完成，需要进行状态转换
        return true;
    }

    @Override
    public Boolean convert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        try {
            return activityUserMapper.updateStatus(convertActivityStatusDTO.getActivityId(),
                    convertActivityStatusDTO.getUserIds(),
                    convertActivityStatusDTO.getTargetUserStatus()) > 0;
        } catch (Exception e) {
            log.warn("convert {} 活动人员列表 {} 状态转化失败",
                    convertActivityStatusDTO.getActivityId(),
                    convertActivityStatusDTO.getUserIds(), e);
            return false;
        }
    }
}
